const BaseService = require('./base')
const { Op } = require('sequelize')
class PermissionService extends BaseService {
	constructor(...args) {
		super(...args)
		this.modelName = 'permission'
	}
	async list(options) {
		return await this.ctx.model.RoleMenu.findAll(options)
	}
	async update(rid, midPrims) {
		// 创建事务
		//1.找到对应的rid 全部删除
		//2. 批量创建
		let transaction
		try {
			transaction = transaction = await this.ctx.model.transaction()
			const findRid = await this.ctx.model.RoleMenu.findOne({
				where: {
					rid: {
						[Op.eq]: rid,
					},
				},
			})
			if (findRid) {
				const res = await this.ctx.model.RoleMenu.destroy(
					{
						where: {
							rid: {
								[Op.eq]: rid,
							},
						},
					},
					{
						transaction,
					}
				)
				if (!res) {
					throw Error
				}
			}

			for (let index = 0; index < midPrims.length; index++) {
				const res2 = await this.ctx.model.RoleMenu.create(
					{
						rid,
						...midPrims[index],
					},
					{
						transaction,
					}
				)
				if (!res2) {
					throw Error
				}
			}

			await transaction.commit()
			return { flag: true, msg: '设置成功' }
		} catch (error) {
			console.log(error)
			await transaction.rollback()
			return { flag: false, msg: '操作失败' }
		}
	}
}

module.exports = PermissionService
